from django.shortcuts import render
from app.models.user import User, Address
from django.core.paginator import Paginator, EmptyPage

# Create your views here.


def user_list(request):
	"""
	查询用户列表
	:param request:HttpRequest, http请求
	:return:用户列表users，每页起始的下标值page_start
	"""
	try:
		page = request.GET.get('page', 1)  # 从URL通过get获取当前的页码数,默认从1开始
		currentpage = int(page)
	except ValueError:
		currentpage = 1
	users = User.objects.all()
	pagenum = 3  # 每页显示的条数
	paginator = Paginator(users, pagenum)
	if currentpage > paginator.num_pages:
		currentpage = paginator.num_pages
	if currentpage < 1:
		currentpage = 1
	# 获取当前页前后两页页码范围
	page_range = list(range(max(currentpage - 2, 1), currentpage)) + list(range(currentpage, min(currentpage + 2, paginator.num_pages) + 1))
	# 加上省略页码标记
	if page_range[0] - 1 >= 2:
		page_range.insert(0, '...')
	if paginator.num_pages - page_range[-1] >= 2:
		page_range.append('...')
	# 加上首页和尾页
	if page_range[0] != 1:
		page_range.insert(0, 1)
	if page_range[-1] != paginator.num_pages:
		page_range.append(paginator.num_pages)
	page_start = (currentpage-1)*pagenum  # 每页起始的下标值
	try:
		posts = paginator.page(currentpage)  # 括号里的是页数，显示指定页码的数据，动态显示数据，所以不能写死了
	except EmptyPage:
		posts = paginator.page(paginator.num_pages)

	return render(request, 'visites/users.html', {'posts': posts, 'page_start': page_start})
